package com.simon.mctm.biz.sys.controller;


import com.simon.mctm.biz.sys.dto.UserDto;
import com.simon.mctm.utils.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.CollectionUtils;

import com.simon.mctm.base.response.DoResponse;
import com.simon.mctm.base.response.PageResponse;
import com.simon.mctm.exception.CheckException;
import com.simon.mctm.exception.OperationFailedException;
import com.simon.mctm.token.TokenValidate;
import com.simon.mctm.base.PageResult;
import com.simon.mctm.biz.sys.bean.User;
import com.simon.mctm.biz.sys.service.UserService;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import java.util.Date;
import java.util.List;


/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author simon
 * @since 2018-06-08
 */
@RestController
@Api(description = "系统用户控制器")
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "添加系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "userDto", value = "系统用户对象", required = true, dataType = "UserDto")
    })
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @TokenValidate
    public DoResponse<?> addUser(@RequestBody UserDto userDto) {
        User user = userService.getUserByUsername(userDto.getUsername());
        if (user != null) {
            throw new OperationFailedException("该系统用户已存在");
        }
        Integer res = userService.addUser(userDto);
        User addUser = userService.getUserByUsername(userDto.getUsername());
        if (res > 0) {
            //设置用户角色
            userService.setRoles(addUser.getId(), userDto.getRoleId());
            //设置用户部门
            userService.setDepts(addUser.getId(), userDto.getDeptId());
            return new DoResponse<>();
        } else {
            throw new OperationFailedException("添加系统用户失败");
        }
    }


    @ApiOperation(value = "获取指定系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "系统用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @TokenValidate
    public DoResponse<?> getUser(@RequestParam Integer id) {
        User user = userService.selectById(id);
        if (user != null) {
            return new DoResponse<>(user);
        } else {
            throw new OperationFailedException();
        }
    }

    @ApiOperation(value = "获取系统用户列表")
    @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @TokenValidate
    public DoResponse<?> getAllUser() {
        EntityWrapper<User> ew = new EntityWrapper<>();
        List<User> userList = userService.selectList(ew);
        if (!CollectionUtils.isEmpty(userList)) {
            return new DoResponse<>(userList);
        } else {
            throw new OperationFailedException();
        }
    }


    @ApiOperation(value = "查询系统用户列表,分页形式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户名", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "int"),
            @ApiImplicitParam(name = "pageNum", value = "pageNum", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", dataType = "int", defaultValue = "10")
    })
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @TokenValidate
    public PageResponse<?> getUserPagedList(@RequestParam String username, @RequestParam Integer status,
                                            @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        if (pageNum == 0 || pageSize == 0) {
            throw new CheckException("页码和单页条目必输");
        }
        List<UserDto> userDtoList = userService.getUserPagedList(username, status, pageNum, pageSize);
        PageResult bPage = userService.calPage(username, status, pageSize);
        if (!CollectionUtils.isEmpty(userDtoList)) {
            return new PageResponse<>(userDtoList, userDtoList.size(),
                    bPage.getTotalElements(), bPage.getTotalPage());
        } else {
            throw new OperationFailedException();
        }
    }

    @ApiOperation(value = "删除系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "系统用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @TokenValidate
    public DoResponse<?> deleteUser(@RequestParam Integer id) {
        Integer res = userService.deleteUser(id);
        if (res > 0) {
            return new DoResponse<>();
        } else {
            throw new OperationFailedException();
        }
    }

    @ApiOperation(value = "更新系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "系统用户id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "userDto", value = "系统用户数据对象", required = true, dataType = "UserDto")
    })
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> updateUser(@RequestParam Integer id, @RequestBody UserDto userDto) {
        User temp = userService.selectById(id);
        if (temp == null) {
            throw new OperationFailedException("该系统用户不存在");
        }
        Integer res = userService.updateUser(id, userDto);
        if (res > 0) {
            return new DoResponse<>();
        } else {
            throw new OperationFailedException();
        }
    }

    @ApiOperation(value = "修改密码", notes = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "rePwd", value = "重复密码", required = true, dataType = "String")
    })
    @RequestMapping(value = "/changePwd", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> changePassword(@RequestParam Integer id, @RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
        //判断新密码不能为空
        if (newPwd == null || rePwd == null || "".equals(newPwd) || "".equals(rePwd)) {
            throw new CheckException("新密码不能为空");
        }

        //判断两次密码是否一致
        if (!rePwd.equals(newPwd)) {
            throw new CheckException("两次新密码不一致");
        }

        //判断用户是否存在和校验密码是否一致 !user.getPassword().equals(Utils.encodeMD5(oldPwd))
        User user = userService.selectById(id);
        if (user == null) {
            throw new OperationFailedException("用户不存在");
        } else {
            if (!Md5Utils.validPassword(oldPwd, user.getPassword())) {
                throw new OperationFailedException("密码错误");
            } else {
                user.setLastpasswordreset(new Date());
                user.setPassword(Md5Utils.getEncryptedPwd(newPwd));
                user.setModifytime(new Date());
                int res = userService.changePassword(user);
                if (res > 0) {
                    return new DoResponse<>();
                } else {
                    throw new OperationFailedException();
                }
            }
        }

    }


    @ApiOperation(value = "冻结用户", notes = "冻结用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/freeze", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> freezeUser(@RequestParam Integer id) {
        User user = userService.selectById(id);
        if (user == null) {
            throw new CheckException("用户不存在");
        } else {
            int res = userService.freezeUser(user);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        }
    }

    @ApiOperation(value = "取消冻结用户", notes = "取消冻结用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/unfreeze", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> unfreezeUser(@RequestParam Integer id) {
        User user = userService.selectById(id);
        if (user == null) {
            throw new CheckException("用户不存在");
        } else {
            int res = userService.unFreezeUser(user);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        }
    }

    @ApiOperation(value = "设置角色", notes = "设置角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "roleIds", value = "角色ids", dataType = "String")
    })
    @RequestMapping(value = "/setRole", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> setRoles(@RequestParam Integer id, @RequestParam String roleIds) {
        User user = userService.selectById(id);
        if (user == null) {
            throw new CheckException("用户不存在");
        } else {
            int res = userService.setRoles(id, roleIds);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        }
    }
}

